package com.wrt.produce.controller;

import java.sql.Connection;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.wrt.produce.source.DynamicDataSource;
import com.wrt.produce.util.DataBaseNameUtil;

import lombok.extern.log4j.Log4j2;

/**
 * 首页接口
 * 
 * @author 文瑞涛
 * @date 2021年7月14日 下午2:58:53
 */
@RestController
@Log4j2
public class IndexController {
	
	@Autowired
	private DynamicDataSource dataSource;

	/**
	 * 当前连接的数据库名称
	 * 
	 * @param request http请求
	 * 
	 * @return 数据库名称
	 */
	@GetMapping("/currentDB")
	public String currentDB(HttpServletRequest request) {
        DataSource tempDataSource = dataSource.getDataSource(request.getSession().getId());
        if (null == tempDataSource) {
        	tempDataSource = dataSource.getDataSource();
        }
		try(Connection c = tempDataSource.getConnection();) {
			return DataBaseNameUtil.getDataBaseNameByUrl(c.getMetaData().getURL());
		} catch (SQLException e) {
			log.error(e.getMessage(), e);
			return "连接数据库错误";
		}
	}
}
